package model

import (
	"context"
	"database/sql"
	"fmt"
	"strings"
	"time"

	"github.com/zeromicro/go-zero/core/stores/builder"
	"github.com/zeromicro/go-zero/core/stores/cache"
	"github.com/zeromicro/go-zero/core/stores/sqlc"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"github.com/zeromicro/go-zero/core/stringx"
)

var (
	sysUserFieldNames          = builder.RawFieldNames(&SysUser{}, true)
	sysUserRows                = strings.Join(sysUserFieldNames, ",")
	sysUserRowsExpectAutoSet   = strings.Join(stringx.Remove(sysUserFieldNames, "create_time", "update_time"), ",")
	sysUserRowsWithPlaceHolder = builder.PostgreSqlJoin(stringx.Remove(sysUserFieldNames, "id", "create_time", "update_time"))

	cachePublicSysUserIdPrefix   = "cache:public:sysUser:id:"
	cachePublicSysUserNamePrefix = "cache:public:sysUser:name:"
)

type (
	SysUserModel interface {
		Insert(ctx context.Context, data *SysUser) (sql.Result, error)
		FindOne(ctx context.Context, id int64) (*SysUser, error)
		Update(ctx context.Context, data *SysUser) error
		Delete(ctx context.Context, id int64) error

		FindOneByName(ctx context.Context, name string) (*SysUser, error)
	}

	defaultSysUserModel struct {
		sqlc.CachedConn
		table string
	}

	SysUser struct {
		Id         int64     `db:"id"`
		DeptId     int64     `db:"dept_id"`     // 部门ID
		Avatar     string    `db:"avatar"`      // 头像
		Name       string    `db:"name"`        // 名称
		Password   string    `db:"password"`    // 密码
		Salt       string    `db:"salt"`        // 加密盐
		Gender     int64     `db:"gender"`      // 性别(0.男 1.女 2.未知)
		Email      string    `db:"email"`       // 邮箱
		Phone      string    `db:"phone"`       // 手机号
		Status     int64     `db:"status"`      // 状态(0.正常 1.冻结 2.离职)
		CreateTime time.Time `db:"create_time"` // 创建时间
		CreateBy   int64     `db:"create_by"`   // 创建者
		UpdateTime time.Time `db:"update_time"` // 更新时间
		UpdateBy   int64     `db:"update_by"`   // 更新者
		DelFlag    bool      `db:"del_flag"`    // 逻辑删除
		Role       string    `db:"role"`        // 角色
	}
)

func NewSysUserModel(conn sqlx.SqlConn, c cache.CacheConf) SysUserModel {
	return &defaultSysUserModel{
		CachedConn: sqlc.NewConn(conn, c),
		table:      `"public"."sys_user"`,
	}
}

func (m *defaultSysUserModel) Insert(ctx context.Context, data *SysUser) (sql.Result, error) {
	query := fmt.Sprintf("insert into %s (%s) values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)", m.table, sysUserRowsExpectAutoSet)
	ret, err := m.ExecNoCacheCtx(ctx, query, data.Id, data.DeptId, data.Avatar, data.Name, data.Password, data.Salt, data.Gender, data.Email, data.Phone, data.Status, data.CreateBy, data.UpdateBy, data.DelFlag, data.Role)
	publicSysUserNameKey := fmt.Sprintf("%s%v", cachePublicSysUserNamePrefix, data.Name)
	m.DelCache(publicSysUserNameKey)
	return ret, err
}

func (m *defaultSysUserModel) FindOne(ctx context.Context, id int64) (*SysUser, error) {
	publicSysUserIdKey := fmt.Sprintf("%s%v", cachePublicSysUserIdPrefix, id)
	var resp SysUser
	err := m.QueryRowCtx(ctx, &resp, publicSysUserIdKey, func(ctx context.Context, conn sqlx.SqlConn, v interface{}) error {
		query := fmt.Sprintf("select %s from %s where id = $1 limit 1", sysUserRows, m.table)
		return conn.QueryRowCtx(ctx, v, query, id)
	})
	switch err {
	case nil:
		return &resp, nil
	case sqlc.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}

func (m *defaultSysUserModel) Update(ctx context.Context, data *SysUser) error {
	publicSysUserIdKey := fmt.Sprintf("%s%v", cachePublicSysUserIdPrefix, data.Id)
	publicSysUserNameKey := fmt.Sprintf("%s%v", cachePublicSysUserNamePrefix, data.Name)
	_, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
		query := fmt.Sprintf("update %s set %s where id = $1", m.table, sysUserRowsWithPlaceHolder)
		return conn.ExecCtx(ctx, query, data.Id, data.DeptId, data.Avatar, data.Name, data.Password, data.Salt, data.Gender, data.Email, data.Phone, data.Status, data.CreateBy, data.UpdateBy, data.DelFlag, data.Role)
	}, publicSysUserIdKey, publicSysUserNameKey)
	return err
}

func (m *defaultSysUserModel) Delete(ctx context.Context, id int64) error {
	publicSysUserIdKey := fmt.Sprintf("%s%v", cachePublicSysUserIdPrefix, id)
	_, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
		query := fmt.Sprintf("delete from %s where id = $1", m.table)
		return conn.ExecCtx(ctx, query, id)
	}, publicSysUserIdKey)
	return err
}

func (m *defaultSysUserModel) formatPrimary(primary interface{}) string {
	return fmt.Sprintf("%s%v", cachePublicSysUserIdPrefix, primary)
}

func (m *defaultSysUserModel) queryPrimary(ctx context.Context, conn sqlx.SqlConn, v, primary interface{}) error {
	query := fmt.Sprintf("select %s from %s where id = $1 limit 1", sysUserRows, m.table)
	return conn.QueryRowCtx(ctx, v, query, primary)
}

func (m *defaultSysUserModel) FindOneByName(ctx context.Context, name string) (*SysUser, error) {
	publicSysUserNameKey := fmt.Sprintf("%s%v", cachePublicSysUserNamePrefix, name)
	var resp SysUser
	err := m.QueryRowCtx(ctx, &resp, publicSysUserNameKey, func(ctx context.Context, conn sqlx.SqlConn, v interface{}) error {
		query := fmt.Sprintf("select %s from %s where name = $1 order by create_time desc limit 1", sysUserRows, m.table)
		return conn.QueryRowCtx(ctx, v, query, name)
	})
	switch err {
	case nil:
		return &resp, nil
	case sqlc.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}
